﻿using System;
using System.Linq;
using System.Collections.Generic;

using TempEmployees.DAL;
using TempEmployees.BLL.Database;

namespace TempEmployees.BLL.EntitiesExtensions
{
    public static class ESemester 
    {
        public static float GetSemesterLengthInMonth(Semester semester)
        {
            TimeSpan timeSpan = semester.EndDate - semester.StartDate;
            return (timeSpan.Days / 30);
        }

        public static Semester GetSemesterByID(int semesterId)
        {
            return DbQuery.GetSingleRow<Semester>("ID", semesterId);
        }

        public static void GetDates(int semesterId, out DateTime startDate, out DateTime endDate)
        {
            using (TempEmpDatabaseDataContext db = new TempEmpDatabaseDataContext())
            {
                Semester semester = db.Semesters.Where(s => s.ID == semesterId).First();
                startDate = semester.StartDate;
                endDate = semester.EndDate;
            }
        }

        public static int GetRelevantSemesterId(DateTime date)
        {
            TempEmpDatabaseDataContext db = new TempEmpDatabaseDataContext();
            var query = (from sem in db.Semesters
                         where sem.EndDate > date
                         orderby sem.EndDate
                         select sem).Take(2);

            if (query.Count() == 0) throw new RecordNotInDbException("Current semester is not in the DB!!");
            if (query.Count() == 1) return query.First().ID;

            List<Semester> semesters = query.ToList();
            Semester currSem = semesters[0];

            TimeSpan fromStart = date - currSem.StartDate;
            TimeSpan fromEnd = currSem.EndDate - date;

            if (fromStart >= fromEnd) return currSem.ID;

            return semesters[1].ID;
        }

        public static int GetRelevantSemesterId()
        {
            return GetRelevantSemesterId(DateTime.Now);
        }

        public static bool IsInSemester(Semester semester, DateTime date)
        {
            return (date >= semester.StartDate && date <= semester.EndDate);
        }
    }
}
